var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    totalPrice: 0,
    // 手动上传还是拍照上传
    wayIndex: 0,
    // 空间列表
    spaceList: ["客厅", "餐厅", "卫生间", "卧室", '厨房', '阳台'],
    // 区域
    areaList: ["墙面", "地面", "台面", "楼梯"],
    // 产品规格
    productList: [],
    // 预算列表
    workArr: [


    ],
    // 是否显示遮罩层
    ispeopleType: false,

    // 	施工明细图
    bricklayDetailProof: [

    ],
    // 显示瓦工日期
    isperiod: true,
    // 施工开始时间
    bricklayBeginDate: "",
    // 施工结束时间
    bricklayEndDate: '',

  },
  // 删除项目
  delItem(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    workArr.splice(index, 1)
    this.setData({
      workArr: workArr
    })
  },
  bindPriceday(e) {
    let index = e.currentTarget.dataset.index

    let workArr = this.data.workArr
    workArr[index].bricklayUnivalent = e.detail.value

    workArr[index].price = workArr[index].bricklayUnivalent / workArr[index].bricklayList.length
    if (workArr[index].accounType == 0) {
      workArr[index].bricklayBudgetAmount = workArr[index].bricklayUnivalent * workArr[index].workNum
    } else {
      workArr[index].bricklayBudgetAmount = workArr[index].bricklayUnivalent * workArr[index].bigarea
    }
    let totalPrice = workArr.reduce(function (prev, cur) {
      return prev + cur.bricklayBudgetAmount
    }, 0);
    this.setData({
      workArr: workArr,
      totalPrice: totalPrice
    })
  },
  // 开工录取
  bindDateChangeState(e) {
    console.log(e)
    this.setData({
      bricklayBeginDate: e.detail.value,
    })
  },
  // 结束施工日期
  bindDateChangeEnd(e) {
    this.setData({
      bricklayEndDate: e.detail.value
    })
  },
  // 隐藏开工日期遮罩层
  hideperiodMask() {
    this.setData({
      isperiod: false
    })
  },
  // 派单
  nextorder() {
  if(this.data.Bricklayer){
    this.setData({
      ispeopleType: false,
      isperiod: false
    })
  }else{
    this.setData({
      ispeopleType: true,
      isperiod: false
    })
  }

  },
  // 确定
  quedin() {
    if (this.data.bricklayDetailProof.length == 0 && this.data.wayIndex == 0) {
      wx.showToast({
        title: '请上传明细',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }

    if (this.data.workArr.some(item => item.bricklayBeginDate == '' || item.bricklayEndDate == '')) {
      wx.showToast({
        title: '您有工期未填写',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    if (this.data.workArr.some(item => item.bricklayUnivalent == '')) {
      wx.showToast({
        title: '您有单价没填写',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    if (this.data.workArr.some(item => item.bricklayList.length == 0)) {
      wx.showToast({
        title: '您有项目未添加工人',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    if (this.data.workArr.some(item => item.accounType == 1 && item.bigarea == '')) {
      wx.showToast({
        title: '您有面积未填写',
        duration: 2500, //持续的时间
        icon: 'none', //图标
      })
      return
    }
    // 瓦工未填写内容
    if (this.data.wayIndex == 1) {
      let wworkArr = this.data.workArr.filter(item => item.worktype == 1)
      if (wworkArr.some(item => item.bricklaySpace == '')) {
        wx.showToast({
          title: '您有空间未填写',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
        return
      }
      if (wworkArr.some(item => item.bricklayRegion == '')) {
        wx.showToast({
          title: '您有铺贴区域未填写',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
        return
      }
      if (wworkArr.some(item => item.bricklayProductSpec == '')) {
        wx.showToast({
          title: '您有产品规格',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
        return
      }
    }

    let t = this
    this.upload(this.data.bricklayDetailProof)
      .then(res => {
        let newArr = []
        t.data.workArr.forEach(item => {
          let obj = {
            accessoriesFlag: item.accessoriesFlag,
            processFlag: item.processFlag,
            planBricklayId: (item.bricklayList.map(item => item.id)).join(","),
            bricklaySpace: item.bricklayRegion,
            bricklayRegion: item.bricklaySpace,
            bricklayProductSpec: '',
            bricklayBudgetSize: item.accounType == 0 ? item.workNum : item.bigarea,
            bricklayUnitPrice: item.price,
            bricklayUnitName: item.accounType == 0 ? '天' : '㎡',
            bricklayPeople: item.bricklayList.length,
            bricklayBudgetAmount: item.bricklayBudgetAmount,
            bricklayBeginDate: item.bricklayBeginDate,
            bricklayEndDate: item.bricklayEndDate,
            bricklayUnivalent: item.bricklayUnivalent
          }
          newArr.push(obj)
        })

        t.saveSuperviseDispatch(res, newArr)
      })





  },
  // 岩板砖家派单接口
  saveSuperviseDispatch(bricklayDetailProof, workArr) {
    let t = this
    wx.showLoading({
      title: '加载中。。。', //提示的内容
      mask: true //显示透明蒙层 防止触摸穿透
    })
    wx.request({
      url: app.globalData.Interfaceurl + 'saveSuperviseDispatch',
      method: "post",
      header: {
        "content-type": "application/x-www-form-urlencoded;charset=UTF-8"
      },
      data: {
        userId: app.globalData.userId,
        token: t.data.token,
        orderId: t.data.orderId,
        bricklayDetailProof: bricklayDetailProof.join(),
        workArr: JSON.stringify(workArr),
        bricklayBeginDate: t.data.bricklayBeginDate,
        bricklayEndDate: t.data.bricklayEndDate
      },
      success: res => {
        wx.hideLoading();
        console.log(res)
        if (res.data.result != -1) {
          this.setData({
            isperiod: false,
            issuccessMask: true
          })
        } else {
          wx.showToast({
            title: res.data.message,
            duration: 2500, //持续的时间
            icon: 'none', //图标
          })
          t.setData({
            token: app.token()
          })
        }




      },
      fail: err => {
        wx.showToast({
          title: '请求失败',
          duration: 2500, //持续的时间
          icon: 'none', //图标
        })
      }
    })
  },
  // 上传附件
  upload(arr) {
    return new Promise((reslove, reject) => {
      if (arr.length == 0) {
        reslove([])
        return
      }
      wx.showLoading({
        title: '上传中...', //提示的内容
        mask: true //显示透明蒙层 防止触摸穿透
      })
      let finishFilesList = []
      arr.forEach((item, index) => {
        wx.uploadFile({
          url: app.globalData.Interfaceurl + 'saveFileUpload',
          filePath: item,
          name: 'file',
          formData: {
            userId: app.globalData.userId,

          },
          header: {
            "content-type": "multipart/form-data"
          },
          success: function (res) {
            finishFilesList.push(JSON.parse(res.data).fileUrl)
            if (index >= arr.length - 1) {
              setTimeout(() => {
                wx.hideLoading();
                reslove(finishFilesList)
              }, 500)
            }
          },
          fail: err => {
            return err
          }
        })
      })
    })
  },
  // 是否添加辅料
  radioaccessories(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    workArr[index].accessoriesFlag = e.detail.value
    this.setData({
      workArr: workArr
    })
  },
  // 是否含加工
  radioprocess(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    workArr[index].processFlag = e.detail.value
    this.setData({
      workArr: workArr
    })
  },

  //面积失去焦点
  bindAreablur(e) {

    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    workArr[index].bigarea = e.detail.value



    let bigarea = workArr[index].bigarea
    let price = workArr[index].price
    let len = workArr[index].bricklayList.length
    workArr[index].bricklayBudgetAmount = bigarea * price * len

    let totalPrice = workArr.reduce(function (prev, cur) {
      return prev + cur.bricklayBudgetAmount
    }, 0);




    this.setData({
      workArr: workArr,
      totalPrice: totalPrice
    })
  },


  // 每天单价失去焦点时
  bindday() {

  },


  //  单价失去焦点的时候
  bindPrice(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    let pricee = e.detail.value - 0
    workArr[index].price = pricee.toFixed(2)



    if (workArr[index].accounType == 0) {
      let workNum = workArr[index].workNum
      let price = workArr[index].price
      let len = workArr[index].bricklayList.length
      workArr[index].bricklayBudgetAmount = workNum * price * len


      let totalPrice = workArr.reduce(function (prev, cur) {
        return prev + cur.bricklayBudgetAmount
      }, 0);

      this.setData({
        totalPrice: totalPrice
      })
    } else {
      let bigarea = workArr[index].bigarea
      let price = workArr[index].price
      let len = workArr[index].bricklayList.length
      workArr[index].bricklayBudgetAmount = bigarea * price * len



      let totalPrice = workArr.reduce(function (prev, cur) {
        return prev + cur.bricklayBudgetAmount
      }, 0);
      this.setData({
        totalPrice: totalPrice
      })
    }

    this.setData({
      workArr: workArr,

    })
  },


  // 跳转员工页面
  gobicklayer(e) {
    let index = e.currentTarget.dataset.index
    let checkoutList = []
    if (this.data.workArr != 0) {
      this.data.workArr.forEach(item => {
        item.bricklayList.forEach(item2 => {
          checkoutList.push(item2.userId)
        })
      })
    }
    if (this.data.userIdList) {
      checkoutList = [...this.data.userIdList, ...checkoutList]
      wx.navigateTo({
        url: '/supervisor/pages/bricklayerList/bricklayerList?worktype=' + e.currentTarget.dataset.worktype + '&&index=' + index + '&&bricklayList=' + JSON.stringify(e.currentTarget.dataset.bricklaylist) + "&&checkoutList=" + JSON.stringify(checkoutList),
      })
    } else {
      wx.navigateTo({
        url: '/supervisor/pages/bricklayerList/bricklayerList?worktype=' + e.currentTarget.dataset.worktype + '&&index=' + index + "&&checkoutList=" + JSON.stringify(checkoutList),
      })
    }
  },





  // 上传明细
  bindUnplone() {
    let t = this
    wx.chooseMedia({
      count: 5 - t.data.bricklayDetailProof,
      mediaType: ['image'],
      maxDuration: 60,
      success(res) {
        console.log(res)
        let bricklayDetailProof = t.data.bricklayDetailProof

        res.tempFiles.forEach(item => bricklayDetailProof.push(item.tempFilePath))
        t.setData({
          bricklayDetailProof: bricklayDetailProof
        })

      }
    })
  },
  // 预览图片
  previewImage(e) {
    let bricklayDetailProof = this.data.bricklayDetailProof
    let url = e.currentTarget.dataset.url
    wx.previewImage({
      current: url, // 当前显示图片的 http 链接
      urls: bricklayDetailProof, // 需要预览的图片 http 链接列表
      success() {

      }
    })
  },
  // 删除图片
  del(e) {
    let bricklayDetailProof = this.data.bricklayDetailProof
    bricklayDetailProof.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      bricklayDetailProof: bricklayDetailProof
    })
  },

  // 隐藏遮罩层
  hideType() {
    this.setData({
      ispeopleType: false
    })
  },
  // 铺贴空间
  bindSpace(e) {
    let workArr = this.data.workArr
    workArr[e.currentTarget.dataset.index].bricklaySpace = this.data.spaceList[e.detail.value]
    this.setData({
      workArr: workArr
    })
  },
  // 铺贴区域
  bindArea(e) {
    let workArr = this.data.workArr
    workArr[e.currentTarget.dataset.index].bricklayRegion = this.data.areaList[e.detail.value]
    this.setData({
      workArr: workArr
    })
  },
  // 产品规格
  bindProduct(e) {
    let workArr = this.data.workArr
    console.log(this.data.designList[e.detail.value], e.detail.value)
    workArr[e.currentTarget.dataset.index].bricklayProductSpec = this.data.designList[e.detail.value].productSpec
    this.setData({
      workArr: workArr
    })
  },
  // 上传明细方式
  bindWay(e) {
    let t = this
    wx.showModal({
      title: '提示',
      confirmColor: "#D6000F",

      content: '如切换到另一种上传方式，您填写的内容将清空，是否确认切换？',
      success(res) {
        if (res.confirm) {
          let index = e.currentTarget.dataset.type
          let workArr = []
          t.setData({
            wayIndex: index,
            workArr: workArr,
            ispeopleType: true
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  // 添加人眼
  bindadd() {
    this.setData({
      ispeopleType: true
    })
  },
  // 添加工人身份
  addtype(e) {
    let typeIndex = e.currentTarget.dataset.type
    let obj = {
      // 工期
      workNum: "0",
      // 瓦工类别
      worktype: '',
      // 预算方式
      accounType: 0,
      // 是否含辅料
      accessoriesFlag: 0,
      // 是否含加工
      processFlag: 0,
      // 瓦工开工日期
      bricklayBeginDate: "",
      // 瓦工收工日期
      bricklayEndDate: "",
      // 空间
      bricklaySpace: "",
      // 区域
      bricklayRegion: "",
      // 产品规格名称
      bricklayProductSpec: "",
      // 工人列表
      bricklayList: [],
      // 预算单价名称 (㎡或天)
      bricklayUnitName: "",
      //  预算金额
      bricklayBudgetAmount: 0,
      // 单价
      price: '',
      // 面积
      bigarea: '',
      bricklayUnivalent: ""
      // bricklayListest: [{


      //   },

      // ]
    }
    if (typeIndex == 1) {

      obj.worktype = 1

    } else if (typeIndex == 2) {
      obj.worktype = 2
    } else if (typeIndex == 3) {
      obj.worktype = 3
    }
    let workArr = this.data.workArr
    workArr.push(obj)
    this.setData({
      ispeopleType: false,
      workArr: workArr
    })
  },








  // 计算方式
  bindaccounType(e) {

    let index = e.currentTarget.dataset.index
    let type = e.currentTarget.dataset.type
    let workArr = this.data.workArr
    workArr[index].accounType = type
    workArr[index].bricklayBudgetAmount = 0
    workArr[index].bricklayRegion = ''
    workArr[index].bricklaySpace = ''
    workArr[index].bricklayUnitName = ''
    workArr[index].price = ''
    workArr[index].bigarea = ''
    workArr[index].bricklayUnivalent = ''
    this.setData({
      workArr: workArr
    })
  },
  // 继续添加
  jixuadd(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    let worktype = workArr[index].worktype
    let orj = {

      // 空间
      bricklaySpace: "",
      // 区域
      bricklayRegion: "",
      // 产品规格名称
      bricklayProductSpec: "",
      // 工人列表
      bricklayList: [],
      // 预算单价名称 (㎡或天)
      bricklayUnitName: "",
      //  预算金额
      bricklayBudgetAmount: "",
      // 单价
      price: '',
      // 面积
      bigarea: '',
      // 每天多少钱
      bricklayUnivalent: "",
    }
    workArr[index].bricklayListest.push(orj)
    this.setData({
      workArr: workArr
    })
  },

  //计算两个时间差  返回天小时分钟
  timediff(begin_time, end_time) {
    //年月日时分秒转换为时间戳
    let beginTime = (new Date(begin_time).getTime()) / 1000;
    let endTime = (new Date(end_time).getTime()) / 1000;
    var starttime = ''
    var endtime = ''
    if (beginTime < endTime) {
      starttime = beginTime;
      endtime = endTime;
    } else {
      starttime = endTime;
      endtime = beginTime;
    }
    //计算天数
    var timediff = endtime - starttime;
    var days = Math.floor(timediff / 86400) + 1;
    // //计算小时数
    // var remain = timediff % 86400;
    // var hours = parseInt(remain / 3600);
    //计算分钟数
    // var remain = remain % 3600;
    // var mins = parseInt(remain / 60);
    // var res = days + '天' + hours + '小时' + mins + '分';
    return days;
  },
  // 开工日期
  bindStateDate(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    workArr[index].bricklayBeginDate = e.detail.value
    workArr[index].bricklayEndDate = e.detail.value
    if (workArr[index].bricklayEndDate != '') {
      workArr[index].workNum = this.timediff(workArr[index].bricklayBeginDate, workArr[index].bricklayEndDate)
    }


    let workNum = workArr[index].workNum
    if (workArr[index].accounType == 0) {
      workArr[index].bricklayBudgetAmount = workArr[index].price * workNum * workArr[index].bricklayList.length
    }
    let totalPrice = workArr.reduce(function (prev, cur) {
      return prev + cur.bricklayBudgetAmount
    }, 0);


    this.setData({
      workArr: workArr,

    })
  },
  // 收工日期
  bindEndChange(e) {
    let index = e.currentTarget.dataset.index
    let workArr = this.data.workArr
    workArr[index].bricklayEndDate = e.detail.value
    if (workArr[index].bricklayBeginDate != '') {
      workArr[index].workNum = this.timediff(workArr[index].bricklayBeginDate, workArr[index].bricklayEndDate)
    }
    let workNum = workArr[index].workNum

    if (workArr[index].accounType == 0) {
      workArr[index].bricklayBudgetAmount = workArr[index].price * workNum * workArr[index].bricklayList.length
    }


    let totalPrice = workArr.reduce(function (prev, cur) {
      return prev + cur.bricklayBudgetAmount
    }, 0);




    this.setData({
      workArr: workArr,
      totalPrice: totalPrice
    })
  },



  // 隐藏遮罩层
  HidedispatcCar() {
    this.setData({
      issuccessMask: false
    })
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2]; //prevPage 是获取上一个页面的js里面的pages的所有信息。 -2 是上一个页面，-3是上上个页面以此类推。\\
    if (this.data.zhuabpai) {

    } else {
      prevPage.setData({
        todo: ''
      })
    }
    prevPage.getOrderDetails()
    wx.navigateBack({
      delta: 1,
    })
    wx.setStorageSync('istab', true)
  },











  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let date = new Date()
    let mouth = date.getMonth() - 0 + 1 >= 10 ? date.getMonth() - 0 + 1 : "0" + (date.getMonth() - 0 + 1)
    let day = date.getDate() - 0 >= 10 ? date.getDate() : "0" + (date.getDate())
    this.setData({
      today: date.getFullYear() + "-" + mouth + "-" + day,
      bricklayBeginDate: date.getFullYear() + "-" + mouth + "-" + day,
      orderId: options.orderId,
      designList: JSON.parse(options.designList),
      Imageurl: app.globalData.Imageurl,
      token: app.token(),

    })


    if (options.Bricklayer) {
      let Bricklayer = JSON.parse(options.Bricklayer)
      let workArr = this.data.workArr



      let obj = {
        // 工期
        workNum: "0",
        // 瓦工类别
        worktype: '',
        // 预算方式
        accounType: 0,
        // 是否含辅料
        accessoriesFlag: 0,
        // 是否含加工
        processFlag: 0,
        // 瓦工开工日期
        bricklayBeginDate: "",
        // 瓦工收工日期
        bricklayEndDate: "",
        // 空间
        bricklaySpace: "",
        // 区域
        bricklayRegion: "",
        // 产品规格名称
        bricklayProductSpec: "",
        // 工人列表
        bricklayList: [Bricklayer],
        // 预算单价名称 (㎡或天)
        bricklayUnitName: "",
        //  预算金额
        bricklayBudgetAmount: "",
        // 单价
        price: '',
        // 面积
        bigarea: '',
        // bricklayListest: [{


        //   },

        // ]
      }
      if (Bricklayer.workType == 1) {
        obj.worktype = 1

      } else if (Bricklayer.workType == 2) {
        obj.worktype = 2
      } else if (Bricklayer.workType == 3) {
        obj.worktype = 3
      }
      workArr.push(obj)
      this.setData({
        ispeopleType: false,
        workArr: workArr,
        Bricklayer:Bricklayer
      })


    }

    if (options.zhuabpai) {
      this.setData({
        zhuabpai: options.zhuabpai,
        userIdList: JSON.parse(options.userIdList),
        bricklayBeginDate: options.bricklayBeginDate,
        bricklayEndDate: options.bricklayEndDate
      })
    }

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})